Skip to content

ci: add a weekly workflow that turns recurring review comments into build rules - #16225

Open
AnkushinDaniil wants to merge 36 commits into
masterfrom
ci/review-rule-bot
Open

AnkushinDaniil wants to merge 36 commits into
masterfrom
ci/review-rule-bot

Conversation

@AnkushinDaniil

@AnkushinDaniil AnkushinDaniil commented Nov 20, 2026 •

Copy link
Copy Markdown
Contributor

Changes

  • Add .github/workflows/rule-bot.yml, a weekly workflow (Monday 04:00 UTC, also workflow_dispatch) that finds review comments reviewers keep writing by hand and turns one such pattern per run into a build rule.
  • Add scripts/rule-bot/: the pipeline as C# file-based apps (rule-bot.cs, rule-bot.helpers.cs), thin shell wrappers for publish, build and generation, prompts, the pattern list, plus tests (test-rule-bot.cs). The bot keeps no state: nothing is committed and nothing is cached between runs. Each run recomputes everything from the GitHub API over a 180-day window (13 files, +3,112 lines). Size against the Python version: tool 853 to 1,353 lines (rule_bot.py and route-b.sh to rule-bot.cs and rule-bot.helpers.cs), tests 556 to 972.

Why

Many review comments repeat the same request (remove dead code, use a throw helper, do not drop a ValueTask, and so on). Across 4,536 PRs updated between 2026-05-19 and 2026-11-19 (18,828 inline review comments), 1,769 matched one of the patterns in scripts/rule-bot/clusters.json. A build rule catches these before review. #16153 and #16161 were built this way by hand. This workflow keeps doing it every week.

How it works

  1. plan: reads every inline review comment created in the last 180 days (GET /repos/{repo}/pulls/comments?since=…, about 300 pages, about 7 minutes) and the review threads of the PRs with a matching comment. Each comment is counted once (by id), so distinct PRs and commenters come from one pass. It counts each pattern against thresholds (≥ 10 PRs, ≥ 3 commenters, ≥ 5 human comments, where a comment with the signed AI-agent footer counts as a bot, ≥ 60% of comments accepted). It then lists the CA/IDE rules that cover the passing patterns and are not enforced on master.

  2. route-b: for patterns that no existing rule covers, Claude writes a new NETH analyzer with tests. It tries one pattern per run, and the analyzer is kept only if:

    • the analyzer tests pass;
    • the same tests fail when the analyzer's Initialize is replaced with a no-op;
    • the diff passes the path check (only new analyzer and test files, plus one appended row in AnalyzerReleases.Unshipped.md).

    The queue order rotates weekly, so with N patterns in the queue, a pattern that produced no analyzer comes up again after N weeks if the queue does not change (a change in the queue shifts the order), and each run makes at most one analyzer generation. A pattern is not retried for 8 weeks after a rule-bot PR for it was opened (read from the PR list, not from stored state).

  3. measure: a full Release build of every CI solution (the build-solutions.yml matrix and the build-tools.yml list) with the candidate rules at warning. Hit counts come from the compiler output, never from grep. The rules are turned on for .cs files outside scripts/ and .github/, and each build that stalls past 30 minutes is retried once. Existing rules are built first, and their logs are sealed before any generated code runs. Builds with a generated analyzer run only if it passed its checks, and their logs count only that analyzer's own id.

  4. propose: counts hits in production code (test and benchmark projects are excluded) and keeps rules with 5–60 production hits. A new analyzer also needs 20 random production hits labelled by a separate Claude pass with ≥ 18/20 true positives for the reason the review comments state (a hit the analyzer flags for another reason does not count). Rules that an open PR sets to warning or error in an .editorconfig are dropped (a PR that only names the rule does not count; the bot pages through every open PR's files, and a failed lookup stops the run). A rule with a production hit in a file the bot may not change (analyzer and generator projects) is skipped. A rule whose rule-bot PR was closed without merge in the last 8 weeks is skipped, a merged one stays out, and nothing is proposed while a PR labelled rule-bot is open.

  5. fix: Claude fixes the production hits (behaviour-preserving changes only). The job then rebuilds the affected solutions, requires 0 hits left, and checks the changed paths.

  6. open-pr: applies the patch on a clean checkout, re-checks the paths and opens a ready PR labelled rule-bot. Reviewers come from CODEOWNERS. The PR body has the rule, the hit counts, 3 example review comments with links, the precision sample (new analyzers) and how to revert.

The jobs that run Claude never get a token that can write to the repository. plan creates a read-only app token (pull-requests: read) to read the review comments; it runs no model. Only open-pr creates a token that can write, and it runs no model and no git hooks. Claude Code ignores Write(...) permission rules, so every file the model may write is granted, and every denied path is blocked, with an Edit(...) rule. The bot may not change .github/, .agents/, scripts/ or any *.md file. The one exception is the appended AnalyzerReleases.Unshipped.md row, so an analyzer PR also needs a *.md code owner. It uses only existing secrets: APP_PRIVATE_KEY with vars.APP_ID (as in bump-version.yml) and CLAUDE_CODE_OAUTH_TOKEN (as in claude-review.yml). flaky-test-fix.yml already opens PRs the same way.

Manual runs default to dry_run: true. A dry run stops after propose and writes the packages and the PR body to the job summary. A run with nothing to build says why in the job summary.

Dry run

The workflow ran locally on this branch before the bot was ported to C# (each run: step executed as written; checkout, artifacts and cache replaced by local equivalents). It used SDK 11.0.100 and all 15 CI solutions, and every build succeeded.

Rule Production hits Test hits Result
IDE0051, IDE0052, IDE0059 7, 28, 20 91 proposed as one package, dropped: already in #16153
CA1512 8 0 proposed, dropped: already in #16161
CA2012 11 157 chosen
CA1510, CA1513 0 0 skipped: already a warning on master
CA1849, IDE0060, CA2213, CA2000, CA1031, CS1591 65 to 27,548 deferred: more than 60 production hits
NETH012 (new analyzer: Task.Delay without the CancellationToken in scope) 0 1 skipped: fewer than 5 production hits

For the new analyzer (this run predates the one-pattern-per-run limit and tried two patterns), the generator skipped the first pattern because the comments do not share one code shape. The second pattern produced NETH012: 11 tests pass, and they fail with the no-op Initialize. It reports nothing in production code, so no PR. These counts match the earlier hand-made PRs: #16153 and #16161 report the same rules with production counts in the same range.

Stateless plan stage (2026-11-21)

Also before the port, the plan steps ran locally against the live API with the 180-day window: 30,184 inline review comments since 2026-05-25, 302 REST pages, 1,154 PRs read in 47 GraphQL queries, 438 s in total. 16 of 20 patterns pass the thresholds. CA1510, CA1513 and CA1507 are skipped (already warnings on master). CA2012 and the #16153 rules (IDE0051, IDE0052, IDE0059) are still in the list to measure; the #16153 rules are dropped later in propose because an open PR already sets them. CA1512 (#16161) is no longer measured: its pattern has 3 human comments in this window, below the threshold of 5.

Tests

  • dotnet run --file scripts/ci/run-script-tests.cs -- scripts/rule-bot: 110 tests pass (the 64 tests of the Python version, ported by name, plus 46 new tests for the guard, the workflow, the route B loop, the Claude Code tool rules, the open-PR check and malformed input files).
  • Equivalence with the Python version, measured at 67b7f65 before the port was slimmed: both ran on the same 4,715 inputs across 18 subcommands (the real 180-day data, real build logs, adversarial patches for the guard). Outside guard --patch, exit codes, stdout and written files match on every input, with two known differences: on invalid UTF-8 in a diff both exit 1 with different error text, and .NET has a newer Unicode table, so code points unassigned in Python's table count as word characters in render keys.
  • guard --patch differs from the Python version on purpose in 1,138 of 1,864 guard inputs. The Python version split patch lines on \r, \f, NEL and LS, while git apply splits on \n only, so a crafted line could hide a file from the guard. The C# guard reads lines as git does and cross-checks git apply --numstat -z. It also accepts an .editorconfig change only as an append at the end of the file, because a section header inserted higher up would move existing rules out of scope, and it accepts a new file only with the exact mode 100644. Each of the 1,138 was classified against git and the Python guard; none is unexplained. Patches are applied with --index, so a new gitignored file such as *.csproj.user also fails the post-apply guard.
  • Slimmed port (rule-bot.helpers.cs 1,722 -> 1,326 lines) against the port at 67b7f65: 7,457 inputs, 4,180 identical, 3,277 differ, 0 unexplained. 3,159 of the inputs put a wrongly typed value in one field of a JSON input file: 980 have the same effect, 2,156 now stop with exit 1 where the earlier port continued, 23 differ only in output text, and none continues where the earlier port failed. Guard: 1,864 inputs, 0 verdict differences; one failing patch reports one extra reason. Classes (one input is in two): wrongly typed fields rejected 2,156, JSON formatting 318, null keys omitted 290, sample selection from the new RNG 169, non-ASCII digits in a log position 168, seed outside long rejected 49, wrongly typed labels.json fields fail closed 28, the same fields with a passing precision result already in route_b.json fail closed 50, unreadable labels.json clears that earlier result 6, non-integer seed syntax rejected 7, non-ASCII digits in a test count fail closed 5, a wrongly typed ok in the route B precision result fails closed 5, wrongly typed fields that change only output text 23, missing hits.json clears an earlier precision result 2, extra guard reason 1, Unicode case folding 1.
  • The route B loop was compared with the shell script it replaces on 519 scenarios, with the model, guard, test and red steps stubbed: 509 are identical. The other 10 are malformed generator output: a non-string skip or summary is formatted differently (3), an empty result file gets the default skip reason (2), a non-UTF-8 test log changes the summary text (2), and a result file with several JSON documents is rejected as no analyzer (3).
  • Trust boundary: each job publishes the tool to $RUNNER_TEMP before any generated change is applied and runs that binary from outside the checkout. A test confirms that a hostile Directory.Build.props in the tree does not affect the guard.
  • actionlint 1.7.12 reports no issues on rule-bot.yml.

Review

/.github and /scripts are code-owned, so this PR needs a code-owner approval. Before the first scheduled run, a maintainer can run it once by hand with dry_run on (the default) and check the summary.

@claude

claude Bot commented Nov 20, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @AnkushinDaniil's task in 1m 42s —— View job


Review of PR #16225 (review rule bot)

  • Read the workflow, scripts, prompts and tests
  • Ran python3 -m unittest discover -s scripts/rule-bot/tests: all tests pass
  • Posted inline findings

The pipeline is well thought out: it counts hits from the compiler output instead of grep, uses a red control for new analyzers, and samples precision with a separate pass. The main problem is the security boundary. The PR body says model jobs can't touch the write token, but they can.

Findings

Severity Where Issue
Critical rule-bot.yml:391-395 open-pr runs git apply fix.patch and only then runs scripts/rule-bot/rule_bot.py guard. The guard is therefore the patched copy, and it runs with the app token in GH_TOKEN and in .git/config (persist-credentials is on by default). A model-written patch can change check_paths and push .github/ or scripts/ changes, or run any code with the write token. The fix job (analyzer.patch applied before the guard on line 339) and route-b.sh have the same problem: the guard runs from a tree the model has already changed. Fix: run the guard from a copy taken before applying the patch (git show HEAD:…), or check git apply --numstat output before applying.
High route-b.sh:15,31 Prompt injection. Anyone who can comment on a PR can write review comments, and they go into EXAMPLES. The model has unrestricted Write/Edit plus dotnet test, so it can run any code while CLAUDE_CODE_OAUTH_TOKEN is in the environment. eval "$test_cmd" also uses the test_class string from the model without checking it. Fix: limit examples to comments by org members or collaborators, limit Write/Edit to the analyzer and test directories, and check test_class against ^\w+$ with no eval.
Medium rule_bot.py:490 The guard allows .props (which can contain MSBuild <Exec>) and .cs files anywhere. The branch is pushed to this repo, so CI on it runs with internal trust. Fix: narrow the allowed paths for each route.
Medium rule_bot.py:179 The gate adds baseline and new distinct counts of PRs and commenters together, so the same people and PRs are counted twice. The commenters >= 3 gate can pass with 2 people. Fix: store the sets and take the union.
Medium repo rules AGENTS.md and .agents/rules/ci-scripts.md say to prefer C# file-based apps over Python and shell for new CI automation. This PR adds about 870 lines of Python and shell, so it should either be ported or the exception explained.
Low rule_bot.py:292 The test exclusion in .editorconfig (top-level *Test* project directories only) differs from scope() (any *Test* directory). Hits in nested Tests/ folders inside production projects are not fixed, yet the rule still applies to them.
Low llm.sh Placeholders are substituted one after another, so a {{RESULT}} or {{IDS}} inside a review-comment body gets expanded too.
Low rule-bot.yml cache Actions cache entries are evicted after 7 days without access, and the job runs weekly. A late or skipped run loses the state, and the next run collects again from baseline.until. That still works but gets more expensive each week.
Low open-pr rule-bot/$SLUG reuses the branch name, so if a closed PR's branch still exists, git push fails.

Not mergeable yet: the Critical and High security issues need fixing first. The Medium items need a fix or a stated reason.

Comment thread .github/workflows/rule-bot.yml Outdated
new_id=()
[ "$ROUTE" = B ] && new_id=(--new-id "$IDS")
git add -N .
python3 scripts/rule-bot/rule_bot.py guard --base HEAD "${new_id[@]}"

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Critical – the path guard runs code from the patch it is checking, in the job that holds the write token.

git apply "$DATA/fix.patch" runs on line 391, before this line. So scripts/rule-bot/rule_bot.py here is already the patched copy. The patch comes from jobs where Claude had unrestricted Edit/Write, and route-b feeds it untrusted review-comment text. If such a patch changes check_paths (or anything else in rule_bot.py), that code runs with GH_TOKEN set to the app token, and with the app token stored in .git/config by checkout (persist-credentials is on by default here). The modified guard then lets .github/, scripts/ and so on go into the pushed branch.

The same problem appears earlier in the chain:

  • In route-b, route-b.sh calls "$here/rule_bot.py" guard/red from the working tree after the model has run.
  • In the fix job, analyzer.patch is applied first, and then the guard on line 339 runs from the working tree.

So the stated boundary ("jobs that run Claude never get a token that can write") can be bypassed. Those jobs can't write directly, but they control code that later runs where the token is.

Suggested fix: in open-pr, run the guard from a copy taken before applying the patch, for example git show HEAD:scripts/rule-bot/rule_bot.py > "$RUNNER_TEMP/rule_bot.py" and use that copy. Better still, run the path check over git apply --numstat/--summary output before applying anything. Also set persist-credentials: false on this checkout and push with an explicit token URL.

@AnkushinDaniil AnkushinDaniil Nov 20, 2026 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in fbb0e54. Every job now copies scripts/rule-bot to $RUNNER_TEMP before applying any generated patch and runs the guard from that copy. The guard checks the patch text (guard --patch) before git apply, and checks the tree again after it. open-pr checks out with persist-credentials: false and passes the token only on the push URL. Tests: the Guard class (including test_patch_changes) in scripts/rule-bot/tests/test_rule_bot.py.

Comment thread scripts/rule-bot/route-b.sh Outdated
jq --arg c "$cluster" '.[$c].new_examples // []' "$data/gates.json" > "$data/route-b-new-examples.json"
jq -s 'add' "$data/route-b-examples.json" "$data/route-b-new-examples.json" > "$data/route-b-all-examples.json"
rm -f "$data/analyzer-result.json"
"$here/llm.sh" "$here/prompts/analyzer.txt" "Read,Glob,Grep,Edit,Write,Bash(dotnet build:*),Bash(dotnet test:*)" \

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

High – prompt injection can lead to arbitrary code execution while CLAUDE_CODE_OAUTH_TOKEN is in the environment.

EXAMPLES contains review-comment bodies, and anyone who can comment on a PR can write those. findings_from does not restrict comment authors to org members. The prompt says to "treat as data", but that is not a security control. The model has an unrestricted Write/Edit and Bash(dotnet test:*), so any code it writes (tests, a Directory.Build.props, rule_bot.py itself) runs in this job with the OAuth token in the environment.

In addition, test_class from the model's JSON is passed through eval on line 31, which allows command injection outside Claude's tool sandbox.

Suggestions:

  • Limit the examples to comments by org members or collaborators (authorAssociation).
  • Limit Write/Edit to the analyzer and test directories, e.g. Write(src/Nethermind/Nethermind.Analyzers/**).
  • Check test_class against ^[A-Za-z0-9_]+$ before using it, and drop the eval.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in fbb0e54. Examples now come only from comments whose authorAssociation is OWNER, MEMBER or COLLABORATOR. Write/Edit are limited to Nethermind.Analyzers/** and Nethermind.Analyzers.Test/**. test_class must match ^[A-Za-z_][A-Za-z0-9_]*$. The test and red runs go through rule_bot.py test/red with an argv list (no eval, no shell) and with CLAUDE_CODE_OAUTH_TOKEN removed from the environment. One risk remains: the model's own dotnet build/dotnet test calls still run while the token is set. Those calls can only build the analyzer projects it may edit, and their inputs now come only from trusted authors.

Comment thread scripts/rule-bot/rule_bot.py Outdated
bad.append(f"{path}: only one appended row for {new_id or 'the new rule'} is allowed")
elif path.startswith(GUARDED_PREFIXES) or path.endswith(".md"):
bad.append(f"{path}: outside the paths the bot may change")
elif not (path == ".editorconfig" or path.endswith((".cs", ".props", ".globalconfig"))):

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Medium – .props and arbitrary .cs paths pass the guard, and the PR branch is pushed to this repo, not a fork.

A .props file can contain <Target>/<Exec>. Because the branch lives in NethermindEth/nethermind and the PR is opened with an app token, CI on it runs with internal-branch trust, not fork isolation. Route A only needs .cs edits plus .editorconfig, and route B only needs files under Nethermind.Analyzers{,.Test}/.

Suggestion: drop .props/.globalconfig and limit route B to those two directories.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in fbb0e54. The guard now allows only .cs files plus a modified .editorconfig, so .props, .globalconfig and .csproj are rejected. Route A may only modify files listed in fix-hits.txt. Route B may also touch the two analyzer projects and append exactly one row to AnalyzerReleases.Unshipped.md. New files must be mode 100644, and symlinks, mode changes, renames and binary patches fail.

Comment thread scripts/rule-bot/rule_bot.py Outdated

def gate_cluster(base, new_rows):
d = cluster_stats(new_rows)
st = dict(n=base["n"] + d["n"], prs=base["prs"] + d["prs"], commenters=base["authors"] + d["commenters"],

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Medium – the gate counts the same PRs and commenters twice.

base["authors"] + d["commenters"] and base["prs"] + d["prs"] add two distinct-counts together. A reviewer who commented both before and after baseline.until is counted twice, and so is a PR that has comments in both periods. Two people commenting in both periods already pass the commenters >= 3 gate, and every weekly run inflates the counts further.

Suggested fix: store the sets of logins and PR numbers in baseline.json (or just the logins/PRs) and take the union.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in fbb0e54 and b0a0221. baseline.json now stores pr_set/author_set, and the gate takes len(base set ∪ new). The baseline counts are rebuilt with the same clusters.json matcher the weekly run uses (2026-05-19..2026-11-19), so the baseline and new rows are counted the same way. Test test_two_people_in_both_periods_fail_the_commenter_gate covers your example.

Comment thread scripts/rule-bot/rule_bot.py Outdated
def overlay(ids, exclude_tests=False):
s = "\n[*.cs]\n" + "".join(f"dotnet_diagnostic.{i}.severity = warning\n" for i in ids)
if exclude_tests:
for sec in ("src/Nethermind/{*Test*,*Benchmark*}/**.cs", "tools/*/{*Test*,*Benchmark*}/**.cs"):

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Low – the test exclusion in .editorconfig doesn't match how scope() decides what counts as a test.

scope() treats a file as a test if any directory under the project matches *Test*/*Benchmark*, for example src/Nethermind/Foo/Tests/x.cs. The .editorconfig section only excludes top-level project directories. A file like that is counted as "test", so it is not fixed, but the rule still applies to it after the PR. CI would then fail on it (if warnings are errors), or the PR would leave hits that aren't mentioned anywhere.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in fbb0e54. scope() now marks a file as a test only by its project directory (src/<x>/<Project>/…), which is the same rule as the .editorconfig glob src/Nethermind/{*Test*,*Benchmark*}/**.cs. Test: test_scope_matches_the_editorconfig_exclusion.

@github-actions

github-actions Bot commented Nov 20, 2026 •

Copy link
Copy Markdown
Contributor

Stateless guest cost

⚠️ Baseline does not match this pull request's base; deltas are suppressed.

Restored from 14d42a1fef58, not this pull request's base (bf30d1b7f911).

Only absolute measurements are shown.

block steps prover cost
11957686 251,692,232 26,847,903,666
11962410 149,158,028 15,829,079,953
11962415 180,209,258 19,290,240,344
11962427 153,151,902 16,139,237,373
11962485 157,259,412 16,790,020,831
25526356 85,493,795 14,363,185,798
25532382 91,363,842 16,317,769,483
25532442 102,121,429 16,609,465,716
25532454 109,141,515 18,243,070,994
25532553 96,008,991 15,889,355,987
25532642 99,756,703 16,614,851,468

f4424f36ec37 (merge commit) · 11 pinned blocks · ziskemu is deterministic, so these figures are exact and any non-zero delta is real.

@AnkushinDaniil

Copy link
Copy Markdown
Contributor Author

@claude review

@claude

claude Bot commented Nov 20, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @AnkushinDaniil's task in 1m 47s —— View job


Re-review of PR #16225 (review rule bot), after fbb0e54 and b0a0221

  • Read the workflow, shell scripts, prompts and rule_bot.py at HEAD
  • Checked the fixes for the earlier findings
  • Ran python3 -m unittest discover -s scripts/rule-bot/tests: all tests pass
  • Reproduced the patch-guard bypass on a scratch repo
  • Posted inline findings

Earlier findings

Earlier finding Status
Critical – guard ran from the patched tree in open-pr ✅ Fixed. open-pr checks the patch with a copy of the guard taken before the patch, applies it, then checks the tree again. It uses persist-credentials: false and passes the token only in the push URL. The tree check is done by git and caught everything I tried.
High – prompt injection; eval of test_class ✅ Fixed. Examples now come only from OWNER, MEMBER or COLLABORATOR comments. Write/Edit are limited to the analyzer projects. test_class is checked against a regex and run as an argv list with the OAuth token removed. The remaining risk (the model's own dotnet build/dotnet test runs while the token is set) is stated and accepted.
Medium – .props and arbitrary .cs files allowed ✅ Fixed. Only .cs files, a modified .editorconfig, and one row in Unshipped.md are allowed. Mode, symlink, rename and binary changes are rejected.
Medium – gate counted PRs and commenters twice ✅ Fixed. Both are now set unions.
Medium – Python/shell instead of a C# file-based app (ci-scripts.md) ⚠️ No reply yet. Either port it or explain the exception in the PR.
Low – scope() vs the .editorconfig test exclusion ✅ Fixed.
Low – reused branch name ✅ Fixed. The branch name now ends in -$GITHUB_RUN_ID.
Low – placeholders expanded inside substituted text ✅ Fixed. Substitution is now a single re.sub pass.

New findings

Severity Where Issue
Medium route-b.sh:11 Bug added in b0a0221. The rebuilt baseline.json has no samples key; ex keeps only [url, author]. Route B now builds analyzers from this week's trusted new_examples only, which is often an empty list. The NETH012 result in the PR body came from the old baseline.
Medium rule_bot.py:502 (patch_changes) guard --patch only sees files with a diff --git header. A traditional --- /dev/null / +++ b/.github/workflows/evil.yml patch returns guard: PASS (0 files) (reproduced), and git apply then creates the file. The tree check in open-pr still catches it. But in measure and fix, this guard is the only check before the build. Use git apply --numstat --summary -z to list the files, or run the tree guard right after applying.
Medium rule-bot.yml:406 open-pr gets fix-hits.txt (the list of files the bot may change) from the fix job's artifact. Code the model controls can run in that job: it can edit Nethermind.Analyzers/*.cs, which the compiler runs during dotnet build, or in route B the generated analyzer runs there. That code can widen the list to any .cs file. Take fix-hits.txt, body.md and candidates.json from rule-bot-result (uploaded by propose) instead.
Low fix job, Edit(src/**/*.cs) The fix prompt can edit analyzer and source-generator sources, and those run inside the compiler during builds while CLAUDE_CODE_OAUTH_TOKEN is set. Narrowing Edit to the files in fix-hits.txt (or excluding Nethermind.Analyzers/**) would close the main way for model-written code to run in that job.
Low .editorconfig guard Any change to .editorconfig passes, so a bot PR could also set existing enforced rules to none. Checking that the .editorconfig diff only appends the overlay sections for $IDS would make this exact.

The write-token boundary now holds: open-pr runs a tree check with git's own parser, from a guard copied before the patch. The remaining issues are a regression in route B and gaps in the checks before open-pr.

Not mergeable yet: three new Medium findings, and the C# port question (Medium) still has no answer.

Comment thread scripts/rule-bot/route-b.sh Outdated

attempt() {
local cluster=$1 why=$2
jq --arg c "$cluster" '[.clusters[$c].samples[]?]' "$here/baseline.json" > "$data/route-b-examples.json"

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Medium – b0a0221 broke this: the analyzer generator no longer gets the baseline examples.

b0a0221 rebuilt baseline.json without the samples key. Each cluster now has only n, valid, human, pr_set, author_set, ex, and ex holds just [url, author], with no body, path or line. So .clusters[$c].samples[]? now returns [], and the prompt's {{EXAMPLES}} gets only this week's new_examples (at most 5, from trusted authors only). That is often zero. With no code shapes to work from, the generator will mostly skip, or guess from why alone. The NETH012 dry run in the PR body used the old baseline, which still had samples.

Fix: put samples back in baseline.json (filtered to OWNER/MEMBER/COLLABORATOR authors, to keep the injection fix), or change this line to read whatever key now holds them. A unit test that checks every route-B cluster has at least one example would catch this next time.

@AnkushinDaniil AnkushinDaniil Nov 20, 2026 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in fb90308. baseline.json has a samples list again for every cluster. It holds up to 5 comments per cluster, from people (not bots) whose author_association is OWNER, MEMBER or COLLABORATOR, and whose comment counts as valid, with the body cut at 500 characters. route-b.sh reads .clusters[$c].samples as before. Test: Baseline.test_route_b_clusters_have_trusted_samples checks that every route B cluster in routes.json has at least one sample with a body from a person.

Comment thread scripts/rule-bot/rule_bot.py Outdated
return bad


def patch_changes(text):

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Medium – guard --patch passes patches that don't use diff --git headers.

patch_changes only notices files that have a diff --git a/X b/X header. git apply also accepts traditional unified diffs, and paths that git quotes ("a/…") don't match \S+ either. Reproduced:

--- /dev/null
+++ b/.github/workflows/evil.yml
@@ -0,0 +1 @@
+on: push

guard --patch → guard: PASS (0 files). git apply then creates .github/workflows/evil.yml. A hunk like this placed after a valid header is also credited to the previous file.

In open-pr, the tree guard that runs after git apply still catches this, so the write token stays safe. But in measure (line 166) and fix (line 316), the patch guard is the only check before git apply and dotnet build. There, an analyzer.patch from a compromised route-b job could drop a Directory.Build.targets that runs during the build.

Fix: let git parse the patch instead of a regex. Use git apply --numstat --summary -z <patch> for the paths and modes, and fail closed if the patch has any ---/+++ pair that isn't in that list. Alternatively, apply the patch and then run the tree guard (guard --base HEAD) before any build, as open-pr does.

@AnkushinDaniil AnkushinDaniil Nov 20, 2026 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in fb90308. patch_changes now tracks hunk line counts, and any ---/+++ header outside a hunk counts as a change. If that header names a file other than the current diff --git file, it is listed as X and rejected. Your example now gives guard: FAIL .github/workflows/evil.yml (exit 1). Also, measure and fix now run the tree guard (git add -N . + guard --new-id) right after git apply, using the copy of the guard made before the patch. Tests: test_patch_changes_sees_files_without_git_header, test_patch_changes_sees_second_file_inside_git_block.

Comment thread .github/workflows/rule-bot.yml Outdated
cp -r scripts/rule-bot "$RUNNER_TEMP/rule-bot"
new_id=()
[ "$ROUTE" = B ] && new_id=(--new-id "$IDS")
python3 "$RUNNER_TEMP/rule-bot/rule_bot.py" guard --patch "$DATA/fix.patch" --files "$DATA/fix-hits.txt" "${new_id[@]}"

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Medium – the file allowlist comes from the job it is meant to limit.

open-pr gets fix-hits.txt from the rule-bot-fix artifact, which the fix job uploads. Arbitrary code can run in that job. The model may Edit(src/**/*.cs), and that includes Nethermind.Analyzers/*.cs, which the compiler runs during the model's own dotnet build. In route B, the generated analyzer also runs there. Code like that can rewrite fix-hits.txt so it lists any .cs file in the repo, and guard --files will then allow changes to those files in the pushed PR. The .github/, scripts/ and non-.cs limits still apply, so the impact stays within .cs files. But "Route A may only modify files listed in fix-hits.txt" doesn't hold.

Fix: get fix-hits.txt (and candidates.json/body.md) from rule-bot-result, which propose uploads before any model edits code. Upload only fix.patch from fix.

@AnkushinDaniil AnkushinDaniil Nov 20, 2026 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in fb90308. rule-bot-fix now uploads only fix.patch. open-pr downloads rule-bot-result (uploaded by propose, before any generated code runs) to $RUNNER_TEMP/rule-bot-result, and takes fix-hits.txt and body.md from there for both guard calls and gh pr create.

@AnkushinDaniil

Copy link
Copy Markdown
Contributor Author

@claude review

@claude

claude Bot commented Nov 20, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @AnkushinDaniil's task in 1m 48s —— View job


Third review of PR #16225 (review rule bot), after fb90308

  • Read rule-bot.yml, route-b.sh, llm.sh, build.sh and rule_bot.py at HEAD
  • Checked the fixes for the second-round findings
  • Ran python3 -m unittest discover -s scripts/rule-bot/tests: all tests pass
  • Tested guard --patch against crafted patches in a scratch repo
  • Posted inline findings

Second-round findings

Finding Status
Medium: route B lost its baseline examples ✅ Fixed. samples is back in baseline.json, limited to trusted authors, and a test checks that every route-B cluster has at least one sample.
Medium: guard --patch missed patches without a diff --git header ✅ Fixed. My earlier --- /dev/null / +++ b/.github/workflows/evil.yml patch now fails the guard. A hunk whose line count is too large and swallows a second file header passes the guard, but git apply rejects it as corrupt, so the file is never created. measure and fix also run the tree guard right after git apply.
Medium: fix-hits.txt came from the fix job's artifact ✅ Fixed. rule-bot-fix now uploads only fix.patch. open-pr takes fix-hits.txt and body.md from rule-bot-result.
Medium: Python and shell instead of a C# file-based app (AGENTS.md, .agents/rules/ci-scripts.md) ⚠️ Still no reply. Port it, or explain the exception in the PR.
Low: the fix job may run Edit(src/**/*.cs) on Nethermind.Analyzers/** ⚠️ Not changed and no reply (rule-bot.yml:331).
Low: the guard accepts any change to .editorconfig ⚠️ Not changed and no reply.

New findings

Severity Where Issue
Medium rule_bot.py:497 (check_paths) With --new-id, any .cs file under the analyzer projects passes with any status, including modify (M) and delete (D) of existing analyzers and their tests. Reproduced: deleting or editing Nethermind.Analyzers/ExistingAnalyzer.cs gives guard: PASS. The PR body says route B may add "only new analyzer and test files". A route-B PR could therefore quietly weaken EmptyCatchBlockAnalyzer and others, and the tree guard in open-pr runs the same check, so it doesn't catch it. Fix: accept only status == "A" under ANALYZER_DIRS (inline suggestion), and add a test.
Low fix / route-b jobs The pre-patch copy in $RUNNER_TEMP/rule-bot is safe from git apply, but not from code running in the same job. Model-written code runs inside the compiler during dotnet build/dotnet test and can rewrite rule_bot.py, build.sh or the route-b.sh script that is still running. In those jobs, the "0 production hits left", tests_ok/red_ok and guard_ok results can therefore be forged. The path checks still hold, because measure and open-pr re-run the guard from a fresh checkout. Hit counts and test results are not re-checked after the fix job, so CI on the bot PR is the only backstop for them. Consider saying this in the PR body, or narrowing Edit as suggested before.

The write-token boundary still holds. Every artifact open-pr relies on now comes either from a job that ran no model or from a patch it checks again from a fresh checkout.

Not mergeable yet: one new Medium (route B can change or delete existing analyzers), and the Medium about porting to C# still has no answer.

Comment thread scripts/rule-bot/rule_bot.py Outdated
bad.append(f"{path}: may only be modified")
elif not path.endswith(".cs") or path.startswith(GUARDED_PREFIXES):
bad.append(f"{path}: outside the paths the bot may change")
elif not (new_id and path.startswith(ANALYZER_DIRS)) and not (status == "M" and path in fix_files):

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Medium: in route B, the guard accepts any change to an existing analyzer, including deleting it.

When --new-id is set, any .cs path under ANALYZER_DIRS passes with any status. That includes M and D on existing files. I checked this against HEAD with guard --patch --new-id NETH099:

  • deleting src/Nethermind/Nethermind.Analyzers/ExistingAnalyzer.cs gives guard: PASS (1 files)
  • modifying the same file also gives guard: PASS (1 files)

The PR body says route B may change "only new analyzer and test files, plus one appended row in AnalyzerReleases.Unshipped.md". With this check, a route-B patch could weaken or remove EmptyCatchBlockAnalyzer, BannedConcurrentDictionaryKeysValuesAnalyzer and others, along with their tests. The edited analyzer would then run in measure and fix and change the hit counts there, and it would ship in the PR as a small diff that is easy to miss next to the new files. The tree guard in open-pr runs the same check_paths, so it doesn't catch this either.

Suggested fix: under ANALYZER_DIRS, accept only status == "A" (Unshipped.md already has its own branch). Add a test that M/D on an existing analyzer fails with new_id set.

Suggested change
elif not (new_id and path.startswith(ANALYZER_DIRS)) and not (status == "M" and path in fix_files):
elif not (new_id and status == "A" and path.startswith(ANALYZER_DIRS)) and not (status == "M" and path in fix_files):

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 7802036. With --new-id, a file under ANALYZER_DIRS now passes only if its status is A. Changes to existing analyzers and tests (M or D) fail unless the file is in fix-hits.txt. Test: Guard.test_route_b_cannot_change_existing_analyzers (M and D of EmptyCatchBlockAnalyzer.cs both fail).

@AnkushinDaniil

Copy link
Copy Markdown
Contributor Author

@claude review

@claude

claude Bot commented Nov 20, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @AnkushinDaniil's task in 27s —— View job


Fourth review of PR #16225 (review rule bot), after 7802036

  • Read the diff from fb90308 to 7802036 (check_paths and a new test)
  • Checked patch_changes again to see how it sets the A status
  • Ran python3 -m unittest discover -s scripts/rule-bot/tests: all tests pass

Third-round findings

Finding Status
Medium: route B could change or delete existing analyzers ✅ Fixed. Under ANALYZER_DIRS, a file now passes only with status A (or M if it is listed in fix-hits.txt). test_route_b_cannot_change_existing_analyzers checks that M and D fail. In patch mode, A is set only by new file mode 100644, and git apply refuses to create a file that already exists. So an existing analyzer can't be overwritten by labelling it as new.
Medium: Python and shell instead of a C# file-based app (AGENTS.md, .agents/rules/ci-scripts.md) ⚠️ Still not answered after four rounds. Either port the scripts, or add a short note to the PR body explaining the exception (for example, that the GraphQL collection and patch parsing were prototyped in Python and will be ported later). Any stated reason resolves this finding.
Low: fix job Edit(src/**/*.cs) reaches Nethermind.Analyzers/**, so code the model writes runs inside the compiler while CLAUDE_CODE_OAUTH_TOKEN is set ⚠️ Not changed and not answered. Path checks still hold, because open-pr checks the patch again from a fresh checkout. But the "0 production hits left" result is only re-checked by CI on the bot PR.
Low: the guard accepts any change to .editorconfig ⚠️ Not changed and not answered. A bot PR could set an existing rule to none. Reviewers would see it in the diff, but the guard doesn't catch it.

New findings

None. The 7802036 change does what it says and doesn't loosen any other check.

Verdict

The security boundary holds:

  • Every artifact open-pr relies on comes either from a job that ran no model or from a patch it checks again with a copy of the guard taken before the patch.
  • Route A can only modify files with listed hits.
  • Route B can only add new analyzer and test files, plus one row in Unshipped.md.

Not mergeable yet: only the C# port Medium is left. One sentence in the PR body explaining why this stays in Python and shell would resolve it. The two Lows can be fixed or answered in a reply.

…ccept only the rule overlay in .editorconfig
@claude

claude Bot commented Nov 23, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @AnkushinDaniil's task in 1m 10s —— View job


Fourteenth review of PR #16225 (review rule bot), after 5d693dc

  • Read the diff from 67b7f65 to 5d693dc (rule-bot.helpers.cs −890/+467 overall, tests updated, unused skip_measure output removed)
  • Ran dotnet run --file scripts/ci/run-script-tests.cs -- scripts/rule-bot: all 90 tests pass
  • Checked the open findings from round 13
  • Checked that the new typed JSON still matches what the workflow reads

Findings from round 13

Finding Status
Medium: the C# port kept a layer that copied Python behaviour (PyRandom, CodePointOrder, a hand-written JSON writer, PyInt/BigInteger, TranslatePattern, untyped Obj/D/S helpers) ✅ Fixed. All of that is gone. Data now goes through typed records (Comment, Gate, PlanFile, HitsFile, …) and System.Text.Json with SnakeCaseLower, so the files keep the field names the workflow's jq calls read (tests_ok, open_prs, counts[].prod). The sample uses a seeded System.Random.Shuffle, sorting is ordinal, and the regexes are .NET [GeneratedRegex]. rule-bot.helpers.cs dropped from 1,722 to 1,317 lines. The guard hardening (git-style line splitting, the git apply --numstat -z check, the end-of-file .editorconfig check) is unchanged, and its tests still pass.
Nit: no job read the skip_measure output ✅ Removed. The summary step still reads skip_measure=true straight from $GITHUB_OUTPUT, which is correct.

New findings

None at Critical, High, Medium or Low. 5d693dc does what it says and doesn't loosen any check:

  • Route A's allowlist still comes from logs that were sealed before any generated code ran.
  • Route B can still only add new analyzer and test files, plus one row in Unshipped.md.
  • open-pr still checks the patch with a tool published before the patch is applied, and its token has no workflows permission.

Nit (not blocking): some numbers in the PR body are out of date. The Changes section says "+3,378 lines" and "tool 853 to 1,732 lines". The tool is now about 1,327 lines (rule-bot.cs plus rule-bot.helpers.cs), and the PR adds about 2,955 lines in total.

Verdict

Mergeable. Every Critical, High and Medium finding from the earlier rounds is either fixed in code or addressed in the design, and no new ones came up. The PR still needs a code-owner approval for /.github and /scripts. Before the first scheduled run, a maintainer should do one manual dry_run and read the job summary, as the PR body suggests.

@AnkushinDaniil

Copy link
Copy Markdown
Contributor Author

@claude review

@claude

claude Bot commented Nov 23, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @AnkushinDaniil's task in 53s —— View job


Fifteenth review of PR #16225 (review rule bot), after 4c48bec

  • Read the diff from 5d693dc to 4c48bec (PrecisionCommand plus one new test)
  • Ran dotnet run --file scripts/ci/run-script-tests.cs -- scripts/rule-bot: all 91 tests pass
  • Checked how the change interacts with the precision ... || true step in propose

What changed

PrecisionCommand now clears any precision result already stored in route_b.json, and saves that, before it reads labels.json. Previously, if labels.json held wrongly typed fields, deserialization threw before the old result was overwritten. The workflow step ends with || true, so the old passing precision.ok = true stayed in place, and propose could accept the analyzer. Now the command still exits 1 on bad labels, but the cleared result is already on disk. propose then reports skip: precision sample failed, so the check fails closed. test_unreadable_labels_clear_earlier_precision covers four bad label shapes (a string line, a bool line, a numeric file, a numeric label) and checks the final verdict from propose.

Edge cases I checked:

  • route_b.json is missing: LoadOr returns an empty state and no early save happens, so nothing changes from before.
  • route_b.json itself is malformed: LoadOr throws before anything is written. propose then can't read it either, so this also fails closed.

Earlier findings

Every Critical, High and Medium finding from rounds 1–14 is still resolved, and this commit doesn't touch the guard, the workflow or the token boundary.

New findings

None.

Nit (not blocking): the PR body still says 91 tests, which matches.

Verdict

Mergeable. It still needs a code-owner approval for /.github and /scripts. Before the first scheduled run, a maintainer should do one manual dry_run and read the job summary.

Read analyzer-result.json fields by JSON kind, so a mistyped skip or
summary no longer discards a passing analyzer.

Stop on rows and fields the previous port rejected: missing required
keys, a null route B cluster or queue, hits without solutions, examples
without url or author, and a validity outside 0 to 1.
@AnkushinDaniil

Copy link
Copy Markdown
Contributor Author

@claude review

@claude

claude Bot commented Nov 23, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @AnkushinDaniil's task in 1m 6s —— View job


Sixteenth review of PR #16225 (review rule bot), after 780a054

  • Read the diff from 4c48bec to 780a054 (rule-bot.helpers.cs +19/−15, three new tests)
  • Ran dotnet run --file scripts/ci/run-script-tests.cs -- scripts/rule-bot: all 94 tests pass
  • Checked how the stricter parsing affects the workflow and the guard

What changed

The commit makes malformed input files stop the command instead of being accepted silently:

  • [JsonRequired] on the key fields of Comment, Gate and Hit. A null RouteBState.Cluster is rejected in the setter.
  • findings now fails when a thread entry in prs.json is null. Before, GetValueOrDefault(...) ?? [false,false] turned it into "unresolved, not outdated". It now fails through the general catch in Run (exit 1), which is fail-closed.
  • RebuildSet fails on a production hit that has no solutions. Hits always sets Solutions = [] and fills it, so real hits.json files aren't affected (RebuildSet is only called from package).
  • route-b fails when route_b_queue is null, and body fails on a validity outside [0, 1] or an example with no url or author.
  • AnalyzerResult is replaced by a Dictionary<string, JsonElement> read through Given(). A wrongly typed field such as "skip": false or "summary": ["x"] no longer throws away the whole result. analyzer and test_class are still checked afterwards: the TestClassName() regex, the src/Nethermind/Nethermind.Analyzers/ prefix plus .cs, and File.Exists. A non-string value (number, array or object raw text) can't pass those checks, so the trust boundary is unchanged.

I checked these edge cases:

  • "analyzer": "a.cs\n" is trimmed to a.cs, and the path check and File.Exists still run on the trimmed value.
  • "skip": true becomes the skip reason "true", which is harmless output text.
  • A thread entry with only one element ([true]) gives IndexOutOfRange, which Run also turns into exit 1.

Earlier findings

Every Critical, High and Medium finding from rounds 1–15 is still resolved. This commit doesn't touch the workflow, Guard, CheckPaths, the deny list or the token handling.

New findings

None.

Nit (not blocking): the null-thread case in findings fails through a NullReferenceException caught by the general handler, not a BotExit with a message. A ?? throw new BotExit(1, "findings: thread state is null") would give a clearer log line. It is fail-closed either way.

Verdict

Mergeable. It still needs a code-owner approval for /.github and /scripts. Before the first scheduled run, a maintainer should do one manual dry_run and read the job summary.

…PRs that enable the rule

Claude Code 2.1.330 ignores Write(path) allow and deny rules for file permission checks; only Edit(path) rules apply and cover Write. Route B could not write analyzer-result.json and the label step could not write labels.json. OpenPrsFor now counts an open PR only when its .editorconfig diff enables the rule, so a PR that only names the id no longer blocks a package.
@AnkushinDaniil

Copy link
Copy Markdown
Contributor Author

@claude review

@claude

claude Bot commented Nov 23, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @AnkushinDaniil's task in 1m 4s —— View job


Seventeenth review of PR #16225 (review rule bot), after f1cab35

  • Read the diff from 780a054 to f1cab35 (rule-bot.yml +1/−1, rule-bot.helpers.cs +21/−4, two new tests)
  • Ran dotnet run --file scripts/ci/run-script-tests.cs -- scripts/rule-bot: all 96 tests pass
  • Checked the new permission rules against the Claude Code permission syntax, and checked how the new duplicate check works

What changed

1. File permissions now use Edit(...) rules only.

  • Route B: RouteBTools grants Edit(src/Nethermind/Nethermind.Analyzers/**), Edit(src/Nethermind/Nethermind.Analyzers.Test/**) and Edit(/<result>).
  • Labelling step: it now grants Edit(/$DATA/labels.json).
  • FixDenyTools: it now emits one Edit(prefix**) per Roslyn project and no longer emits Write(...).

Claude Code applies Edit rules to every built-in file-writing tool, so the allow and deny lists still cover Write. In the old version, an ignored Write(...) rule could leave the deny list with a gap; this change removes that risk.

The leading / is correct. $DATA and resultPath are absolute paths, so / + /home/... becomes //home/..., which is the absolute-path form. A single / would have been read as relative to the settings file. test_file_tool_rules_use_edit checks this, and also checks that the workflow has no Write( left.

2. A rule is only treated as a duplicate if an open PR actually enables it.
OpenPrsFor now fetches each candidate PR's .editorconfig patches. It counts the PR only if one of them adds a dotnet_diagnostic.<id>.severity = warning|error line.

It fails closed in two ways:

  • If the API call fails (non-zero exit), the PR still counts.
  • If a patch is too large for GitHub to return, the patch is null and becomes the ? marker, so the PR still counts.

The test covers five cases: enable, API error, set to none, unknown patch, and a PR that only mentions the rule.

Earlier findings

Every Critical, High and Medium finding from rounds 1–16 is still resolved. This commit doesn't touch Guard, CheckPaths, the token handling or the order of the patch-guard steps.

New findings

Severity Where Issue
Low rule-bot.helpers.cs:719 (EnablesRule) Only *.editorconfig patches are checked, the regex is case-sensitive, and it needs the exact dotnet_diagnostic.<id>.severity key. An open PR is therefore not seen as a duplicate if it enables the rule in any of these ways:
• a .globalconfig file
• <WarningsAsErrors> in a .props file
• Warning with a capital W
• a category-wide dotnet_analyzer_diagnostic.category-*.severity

The old check (the ID appears in the title or body) caught these. The cost is low: at worst the bot opens a PR that overlaps with one a human reviewer can see. To close the gap, include *.globalconfig in the select, add RegexOptions.IgnoreCase, or treat a PR whose title names the ID as a duplicate as before.

No Critical, High or Medium findings.

Verdict

Mergeable. The PR still needs a code-owner approval for /.github and /scripts. Before the first scheduled run, a maintainer should run the workflow once by hand with dry_run on and read the job summary.

@stdevMac stdevMac left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 — Verify that precision labels cover the sampled diagnostics

scripts/rule-bot/rule-bot.helpers.cs:1021–1042 checks the number of labels and positive verdicts, but never checks that the labels correspond to the hits in sample.json. A labeling response with duplicate entries or entries for different hits can pass the precision gate, and propose treats that result as sufficient to select the new analyzer.

Please pass the saved sample into the precision check, require exactly one label for each sampled diagnostic, and cover duplicate and mismatched labels in the gate tests.

🤖 AI agent (Codex / GPT-6.2-Sol) on behalf of @stdevMac

@AnkushinDaniil

Copy link
Copy Markdown
Contributor Author

@claude review

@claude

claude Bot commented Nov 25, 2026

Copy link
Copy Markdown
Contributor

Claude Code is working…

I'll analyze this and get back to you.

View job run

@claude

claude Bot commented Nov 25, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @AnkushinDaniil's task in 1m 16s —— View job


Eighteenth review of PR #16225 (review rule bot), after 75d3579

  • Read the diff from f1cab35 to 75d3579 (precision --sample, SameHits, matches_why, the new arraypool reason, and four new tests)
  • Ran dotnet run --file scripts/ci/run-script-tests.cs -- scripts/rule-bot: all 99 tests pass
  • Checked that the new precision gate matches what sample writes and what the workflow passes in

What changed

1. Each precision label must match a sampled hit (this addresses stdevMac's P2). Precision now receives sample.json. SameHits compares the labels and the sample as multisets of (file, line), and the gate also needs sample.Count == need. Duplicate labels, labels for other files or lines, and a sample that differs from the labelled hits now all fail. The check fails closed: a missing sample.json gives an empty list, so the gate fails, and paths written in another form (for example absolute paths) don't match, so it fails too. Two hits on the same line in different columns are handled correctly by the multiset comparison. The workflow passes the same sample.json that the sample command writes earlier in that step.

2. Only labels that match the stated reason count as true positives. A true positive now needs matches_why == true. A missing or null value does not count, so this also fails closed. The arraypool reason in routes.json now names the code shape the review comments actually ask for.

Earlier findings

Every Critical, High and Medium finding from rounds 1–17 is still resolved. These commits don't touch the guard, the deny list or the token handling.

New findings

Severity Where Issue
Low rule-bot.helpers.cs:1205 (Body) The precision sample in the PR body leaves out matches_why. A hit labelled true_positive with matches_why: false does not count toward the gate, but in the list it looks the same as one that does. The list can then show more true positives than the "N/20" line above it. Showing matches_why would make the two agree.

Nit: the PR body's Tests section says 97 tests. There are now 99.

Verdict

Mergeable. There are no Critical, High or Medium findings, and stdevMac's P2 is fixed in code and covered by tests. The PR still needs a code-owner approval for /.github and /scripts. Before the first scheduled run, a maintainer should run the workflow once by hand with dry_run on.

@AnkushinDaniil

Copy link
Copy Markdown
Contributor Author

@claude review

@claude

claude Bot commented Nov 25, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @AnkushinDaniil's task in 48s —— View job


Nineteenth review of PR #16225 (review rule bot), after cf1031a

  • Read the diff from 75d3579 to cf1031a (Body change in rule-bot.helpers.cs and one new test)
  • Ran dotnet run --file scripts/ci/run-script-tests.cs -- scripts/rule-bot: all 100 tests pass
  • Checked that the new output matches the precision gate

What changed

Each line of the precision sample in the PR body now shows matches stated reason: True|False|None (rule-bot.helpers.cs:1207). This fixes the Low from round 18. The body uses the same MatchesWhy field as the gate at line 1024, which counts a label only when it is true_positive and MatchesWhy == true. A missing value prints as None, and the gate doesn't count it either. So the list now matches the "N/20" line above it. test_body_shows_whether_each_sampled_label_matches_the_stated_reason checks both the True and the False case.

Earlier findings

Every Critical, High, Medium and Low finding from rounds 1–18 is now resolved. This commit only changes how the body text is formatted. It doesn't touch the guard, the deny list, the precision gate, the workflow or token handling.

New findings

None.

Nit (not blocking): the PR body's Tests section says 97 tests. The suite now has 100.

Verdict

Mergeable. The PR still needs a code-owner approval for /.github and /scripts. Before the first scheduled run, a maintainer should run the workflow once by hand with dry_run on and read the job summary.

Comment thread scripts/rule-bot/rule-bot.helpers.cs Outdated

internal static async Task<List<long>> OpenPrsFor(string ruleId, CancellationToken token)
{
var output = await Gh(["pr", "list", "-R", Repo, "--state", "open", "--search", $"{ruleId} in:title,body", "--json", "number", "--limit", "20"], token, check: false);

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

A PR can enable the rule only in .editorconfig, and a failed search also looks like an empty result. Page through open PRs, check their diffs for the rule, and stop on lookup failure before opening a duplicate.

Comment thread scripts/rule-bot/rule-bot.helpers.cs Outdated
{
long prs = rows.Select(r => r.Pr).Distinct().Count(), commenters = rows.Select(r => r.Author).Distinct().Count(), human = rows.Count(r => !r.Bot), valid = rows.Count(CountedValid);
var validity = rows.Count > 0 ? Round2((double)valid / rows.Count) : 0.0;
var fails = new (string Name, bool Ok)[] { ("prs", prs >= 10), ("commenters", commenters >= 3), ("human", human >= 5), ("validity", validity >= 0.6) }

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Rounding first lets 28/47 (59.57%) pass the 60% gate. Use rows.Count > 0 && valid * 5 >= (long)rows.Count * 3 for the gate and round only the displayed value.

@marcindsobczak marcindsobczak left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Checked at cf1031aa01:

  • test-rule-bot.cs through run-script-tests.cs: 100/100. Four mutants of rule-bot.helpers.cs, all killed: no git apply --numstat cross-check in Guard (1 test fails), no FixAllowed in CheckPaths (1), no SameHits in Precision (3), no prefix check in AppendedEditorConfigLines (1).
  • The measure path with the bot's own commands (overlay --exclude-tests, build.sh, hits, package, guard) on the seven Roslyn projects, with 14 of the 15 route-A ids that are not enforced on master (all but CS1591).
  • All 85 entry points under scripts/ and .github/actions/, built with that overlay the way "Check C# CI scripts" builds them, and again with only the overlay fix writes for the unused package.
  • catalog with the --sdk path the workflow passes and with the SDK folder that holds the analysislevel_* files; RecentlyTried with a merged route-B PR.
  • GuardedPrefixes matches ci-change-guard.yml, and measure-route-b runs only when route-b reports passed.

The guard and the token boundary held in everything I ran. The two Medium points concern the bot's output. For today's candidate ids, some hits in the Roslyn projects and in scripts/ are hits the bot cannot fix, and a failed fix comes back every week.

Verdict: changes needed — the bot can get stuck on a package it cannot fix, and its [*.cs] overlay reaches scripts it neither builds nor may change.

🤖 AI agent (Claude Code / Opus 5.5) acting on behalf of @marcindsobczak.

{
var chosen = Load<CandidatesFile>(Path.Combine(data, "candidates.json")).Chosen ?? throw new BotExit(1, "package: no chosen candidate");
var hits = Load<HitsFile>(Path.Combine(data, "hits.json"));
var mine = hits.Hits.Where(x => chosen.Ids.Contains(x.Id) && x.Scope == "prod").ToList();

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[possible issue] Medium — a package with a production hit in an analyzer or generator project can never pass fix, and it is chosen again every week.

Scope() (L590-596) calls Nethermind.Analyzers and the generator projects prod, so this line puts their hits into fix-hits.txt. The fix model is denied those paths (FixDenyTools, rule-bot.yml:441) and CheckPaths rejects them (L847), so the check at rule-bot.yml:456 always fails. No PR is opened, and RejectedIds reads only closed PRs (L509). So next week propose picks the same package first again (L782), ahead of every other route-A package.

At this head, overlay + build.sh + hits on the seven Roslyn projects give IDE0051 at Nethermind.Serialization.SszGenerator/SszType.cs:465 and IDE0059 at Nethermind.Analyzers/SpanToArrayAtCallSiteAnalyzer.cs:119 (the unused package of the dry run). package lists both, and guard fails an edit to either with "not a file with a listed hit", although both files are listed.

Suggest: in propose, count the hits that FixAllowed rejects, and skip or defer such a package with that reason.

🤖 AI agent (Claude Code / Opus 5.5) acting on behalf of @marcindsobczak.

internal static string Overlay(IEnumerable<string> ids, bool excludeTests = false)
{
var list = ids.ToList();
var output = new StringBuilder("\n[*.cs]\n");

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[possible issue] Medium — the [*.cs] overlay also turns the rule on in scripts/ and .github/actions/ (their own .editorconfig files have no root = true). measure never builds those (CiSolutions, L625-632), and the bot may not change them (GuardedPrefixes). The root Directory.Build.props sets TreatWarningsAsErrors=true, and the file-based apps inherit it.

At this head, with the overlay that fix appends for the unused package, run-script-tests.cs -- --check scripts/rpc-bench/test-json-bench-reuse.cs fails with error IDE0051 at scripts/rpc-bench/run-json-bench.cs:461 and :463: that test includes the file with SCRIPT_TEST, which drops the only uses (run-json-bench.cs:49, :71). Without the overlay it passes. Other candidate ids give CA1031/CA1849/CA2000 errors there too (also in gcp-runner); CA2012 gives none. So a bot PR for IDE0051 would fail "Check C# CI scripts" on hits the bot neither counted nor may fix.

Suggest: append a none section for {scripts,.github}/**.cs next to the test sections (and accept it in OverlaySections). Alternatively, build the scripts in measure and drop any package with hits there.

🤖 AI agent (Claude Code / Opus 5.5) acting on behalf of @marcindsobczak.

Comment thread .github/workflows/rule-bot.yml Outdated
run: |
RULE_BOT_DENY=$("$RUNNER_TEMP/rule-bot/rule-bot" deny-tools)
export RULE_BOT_DENY
bash "$RUNNER_TEMP/rule-bot/llm.sh" "$RUNNER_TEMP/rule-bot/prompts/fix.txt" "Read,Glob,Grep,Edit(src/**/*.cs),Edit(tools/**/*.cs),Bash(dotnet build:*)" \

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[possible issue] Low — the fix prompt's "unfixable" list has nowhere to go. prompts/fix.txt (lines 8, 10, 15) tells the model to leave or suppress a site it cannot fix and to list it in {{RESULT}} ($DATA/fix-result.json). These tools grant no Edit on that file, and no step reads it. Route B and the label step do grant their result files (RouteBTools in rule-bot.helpers.cs:1109, and line 347 here).

A site left in place fails line 456. A #pragma or SuppressMessage passes the 0-hits check and the guard (which checks paths, not content), and the body then says "all fixed in this PR" (rule-bot.helpers.cs:1197).

Suggest: grant Edit(/$DATA/fix-result.json) and put its unfixable list into the body. Alternatively, drop the suppression clause and fail the guard on added #pragma warning disable or SuppressMessage lines.

🤖 AI agent (Claude Code / Opus 5.5) acting on behalf of @marcindsobczak.

Comment thread scripts/rule-bot/rule-bot.helpers.cs Outdated
{
var rows = EditorConfigRules(ReadText(Path.Combine(repo, ".editorconfig")));
var sdkDefaults = new Dictionary<string, string>();
foreach (var file in GlobIn(Path.Combine(sdk, "analyzers/build/config"), "analysislevel_", "_default.globalconfig"))

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[possible issue] Low — the SDK half of catalog reads a folder that does not exist. The workflow passes --sdk "$DOTNET_ROOT/sdk/$(dotnet --version)" (rule-bot.yml:63), and this line looks in <sdk>/analyzers/build/config. With SDK 11.0.100 that folder is missing: the analysislevel_*_default.globalconfig files are in sdk/11.0.100/Sdks/Microsoft.NET.Sdk/analyzers/build/config. Entries turns the missing folder into an empty list, so sdkDefaults is always empty. test_sdk_default_warning_counts passes only because it injects the dictionary.

Today nothing changes: no route-A id is warning in those files, and catalog writes the same catalog.json with either path. If the folder is read, the last file in directory-enumeration order wins, not the effective analysis level.

Suggest: use the Sdks/Microsoft.NET.Sdk path, read only the file of the effective analysis level, and fail when the folder is missing. Or drop the SDK part.

🤖 AI agent (Claude Code / Opus 5.5) acting on behalf of @marcindsobczak.

Comment thread scripts/rule-bot/rule-bot.helpers.cs Outdated
internal static HashSet<string> RecentlyTried(IEnumerable<BotPr> botPrs, IEnumerable<string> clusters, DateOnly today)
{
var keys = clusters.ToList();
return botPrs.Where(pr => DaysSince(today, pr.CreatedAt) < CooldownDays)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[possible issue] Low — 56 days after a route-B PR is opened, its cluster comes back even if the PR was merged, and the bot writes a second analyzer for the same pattern. This check ignores the PR state.

Route A has an end state: a merged rule is warning under [*.cs], so catalog marks it enforced. Route B has none. routes.json keeps the cluster with no ids, and the gates keep passing on the comments that predate the analyzer for the rest of the 180-day window.

Probe at this head: a MERGED PR rule-bot/sleep-neth012-… opened on 2026-10-05 gives RecentlyTried = [sleep] on 2026-11-23 and [] on 2026-11-30. The next attempt gets a new NETH id (L558). With 5 or more production hits it opens an overlapping PR; otherwise it spends a generation and the generated-analyzer matrix.

Suggest: keep a cluster out for good once a route-B PR for it is MERGED, or until comments newer than the merge pass the gates again.

🤖 AI agent (Claude Code / Opus 5.5) acting on behalf of @marcindsobczak.

throw new BotExit(1, $"collect: GitHub API failed: {string.Join(' ', args.Take(3))}");
}

internal static bool IsBot(string name) => Bots.Contains(name) || name.EndsWith("[bot]", StringComparison.Ordinal);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[question] Low — should comments that agents post from members' accounts count as hand-written? IsBot and Bots (L118) look only at the login, and Slim takes Bot from User.Type. So an agent-written inline comment posted from a member's account counts toward human and commenters, is valid as likely (CountedValid), and can be one of the TrustedExamples sent to the generator.

On this PR, three member reviews are signed "🤖 AI agent (…) on behalf of @…" in the review body only; their inline comments, which are what collect reads, carry no such line. So a footer check in Slim would catch only agents that sign every inline comment.

The PR body describes the input as comments "reviewers keep writing by hand". If they should not count, Slim could mark rows that carry the footer as Bot (signed comments only); if they should, a sentence in the PR body would settle it.

🤖 AI agent (Claude Code / Opus 5.5) acting on behalf of @marcindsobczak.

Comment thread scripts/rule-bot/build.sh Outdated
mkdir -p "$logs"
log="$logs/$(printf '%s' "$solution" | sed 's#/#__#g').log"
echo "build: dotnet build $solution -c Release $*"
dotnet build "$solution" -c Release -p:TreatWarningsAsErrors=false -p:EnforceCodeStyleInBuild=true \

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[suggestion] Low — this build has no stall guard. build-solutions.yml builds the three src/Nethermind solutions under run-with-stall-watchdog and keeps scheduler tracing for EthereumTests, "the solution that has deadlocked". Here a stall runs until timeout-minutes: 90 (rule-bot.yml:93, :215). With fail-fast and the failure/cancelled conditions on route-b and propose (rule-bot.yml:156, :273), one stall ends the whole week's run with no summary. The watchdog alone would not prevent that: on a stall it exits 1 (scripts/ci/stall-watchdog.md:11-12).

Suggest: run the build under the watchdog (or timeout) and retry it once after a stall.

🤖 AI agent (Claude Code / Opus 5.5) acting on behalf of @marcindsobczak.

…ision gate, scope overlay, SDK config path, stall retry

@svlachakis svlachakis left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

  • Low - rule-bot.yml:526 tests the output of gh pr list but ignores its exit status. A failed lookup can let the publish step continue. Assign the command output first and fail the step on error before checking whether it is empty.

@AnkushinDaniil

Copy link
Copy Markdown
Contributor Author

@claude review

@claude

claude Bot commented Nov 29, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @AnkushinDaniil's task in 2m 24s —— View job


Twentieth review of PR #16225 (review rule bot), after 755043d

  • Read the diff from cf1031a to 755043d (a0f3de7 and 755043d)
  • Checked the fixes for the open findings from marcindsobczak, benaadams and svlachakis
  • Ran dotnet run --file scripts/ci/run-script-tests.cs -- scripts/rule-bot: all 110 tests pass
  • Checked that analysislevel_11_default.globalconfig exists under sdk/11.0.100/Sdks/Microsoft.NET.Sdk/analyzers/build/config, and that no project sets AnalysisLevel or AnalysisMode. The new path is correct, and the default file is the effective one.
  • Probed the new suppression check against patches with unusual headers

Earlier findings

Finding Status
Medium (marcindsobczak): a package with a production hit in a Roslyn project can never pass fix, and it is chosen again every week ✅ Fixed. Propose uses Fixable to count the hits that FixAllowed rejects and gives the package skip: N prod hits in files the bot may not change. This covers route A and route B.
Medium (marcindsobczak): the [*.cs] overlay turns the rule on in scripts/ and .github/, which are never built or fixed ✅ Fixed. Overlay(excludeTests: true) adds a [{scripts,.github}/**.cs] section with none, and OverlaySections accepts it. The overlay in the bot's PR therefore leaves the CI scripts unchanged. The glob is relative to the root .editorconfig and matches files directly under scripts/ too.
Medium (benaadams): the open-PR lookup can't tell a failure from an empty result, and the old search matched PR text instead of what the PR changes ✅ Fixed. OpenEditorConfigPatches pages through every open PR with gh api --paginate, uses check: true on each call, and fails on an unreadable PR number. It reads each PR's file list once and reuses it for every rule ID, and skips the lookup when only route-B packages remain.
Medium (benaadams): the validity gate rounded first, so 28/47 passed ✅ Fixed. The gate now compares integers (valid * 5 >= n * 3). Only the displayed value is rounded.
Low (svlachakis): [ -n "$(gh pr list …)" ] ignored the exit status ✅ Fixed. The output is assigned first, so set -e stops the step if the command fails.
Low (marcindsobczak): the unfixable list in the fix prompt went nowhere, and suppressions could pass ✅ Fixed. The prompt now forbids every suppression. Suppressions() makes guard --patch fail on any added #pragma warning disable or SuppressMessage outside the analyzer projects. fix-result.json can be written and is printed when hits are left. The tree-mode guard in open-pr doesn't run this check, but the patch-mode guard runs first on the same patch, so the check still applies. A patch without a//b/ prefixes can't skip it: PatchChanges reports those headers as X and the guard fails.
Low (marcindsobczak): catalog read a folder that doesn't exist ✅ Fixed. SdkDefaultsFile reads the analysislevel_<TFM major>_default file from Sdks/Microsoft.NET.Sdk, and the run stops if the file or the netN.0 TargetFramework is missing.
Low (marcindsobczak): a merged route-B cluster came back after 56 days ✅ Fixed. A MERGED PR keeps its cluster out for good.
Low (marcindsobczak): comments that agents post from member accounts counted as written by hand ✅ Fixed. Slim marks a comment as a bot comment when its body has the signed 🤖 AI agent … on behalf of @ footer. The PR body now says this.
Low (marcindsobczak): build.sh had no stall guard ✅ Fixed. Each build runs under timeout (default 30 minutes plus 1 minute before the kill) and is retried once on exit code 124 or 137. Two attempts take about 62 minutes, which fits inside timeout-minutes: 90.

New findings

No Critical, High or Medium findings. None of these commits loosens the guard, the deny list or the token handling.

Nits (not blocking):

  • RecentlyTried now keeps merged route-B clusters out for good, but plan reads at most 100 rule-bot PRs (--limit 100). After about 100 weekly bot PRs, the oldest merged clusters drop off the list and become eligible again. Raising the limit or paginating would make "for good" hold.
  • OpenEditorConfigPatches makes one API call per open PR (plus pagination) with github.token, which allows about 1,000 requests per hour per repository. That is fine at today's number of open PRs, but the call count grows with the open-PR backlog.
  • The PR body's Changes section still says "+3,112 lines". The diff now adds 3,316.

Verdict

Mergeable. Every Critical, High and Medium finding from rounds 1–19 and from the human reviews is fixed in code and covered by tests. The PR still needs a code-owner approval for /.github and /scripts. Before the first scheduled run, a maintainer should run the workflow once by hand with dry_run on and read the job summary.

@svlachakis svlachakis left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

My previous Low is fixed. The open-PR lookup now fails the publish job on a GitHub error and exits before patch application when a bot PR is open. The CI change guard is the only failing check.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

6 participants